// miniprogram/pages/SupportPage/questions/questions.js
const util = require("../../../utils/util");
const db = wx.cloud.database()
const dbCmd = db.command;

let superArgs = ""; //存放来自上级页面传入的参数
let quesTitle = ""; //存放问卷标题
let quesName = ""; //存放问卷的集合名称, 比如"ques-onlineDating"
let id = 0; //存放问卷的id
var quesDetailVar = []; //存放问卷内容
let userInfoQuestions_2 = ""; //存放问卷页面所获取的用户信息缓存, 并保存与当前页面的变量中
let loginStatus = false; //用户登录状态
let pageExit = false; //若为true, 则退出当前页面
let ansSet = new Set(); //用于存放用户回答的题目
let sumAsk = 0;
const MAX_LIMIT = 20;//云数据库每次限制读取20条


function setUserInfo(option) {
    userInfoQuestions_2 = option.data.event.userInfo;
    loginStatus = true;
}


Page({
    data: {
        quesDetail: [], //存放传入页面的问卷内容
        title: "", //问卷标题
        loginStatus: false,
        userInfoQuestions: "", //存放问卷页面所获取的用户信息缓存
        changed: {}, //存放用户作答的键值对
        popUpShow: false,
        popUpMsg: '', //弹窗的提示语句
        pageExit: false, //若为true, 则退出当前页面
        autoAnsBtn: false//是否
    },
    onLoad: function (options) {

        let that = this; //暂时保存this指针, 后面在success回调函数中使用
        wx.getStorage({
            key: "userInfo_2",
            success(res) {
                that.setData({
                    userInfoQuestions: res.data.event.userInfo
                });
                setUserInfo(res);
            }
        });
        superArgs = Object.values(options);
        quesName = superArgs[1];
        quesTitle = superArgs[2];
        sumAsk = superArgs[3];

        this.getData();
    },
    getData() { //从后台获取问卷目录
        let that = this;
        const batchTimes = Math.ceil(sumAsk / MAX_LIMIT);

        quesDetailVar = [];

        for (let i = 0; i <= batchTimes; i++) {
            console.log("\n\nquesName: ", quesName)
            db.collection(quesName).skip(i * MAX_LIMIT).get({
                complete: function (res) {
                    // quesDetailVar = quesDetailVar.concat(res.data);
                    quesDetailVar = quesDetailVar.concat(res.data);
                    quesDetailVar.sort(that.quesCompare("num"));
                    that.setData({quesDetail: quesDetailVar});
                }
            });
        }


        that.setData({title: quesTitle});
        if (that.data.title === "2019在校大学生消费与借贷行为调查问卷")
            that.setData({
                autoAnsBtn: true
            })

        that.initQuestionPage(); // 用户问卷的回答统计变量初始化
    },
    /*
    * 利用集合
    * @function
    * */
    closeQuestion(e) {
        if (ansSet.size !== Object.keys(this.data.quesDetail).length) {
            //如果没有回答全部的问题就无法交卷
            let msg = "还没有完成问卷喔~ ";
            this.setData({
                popUpMsg: msg,
                popUpShow: true,
            })
        } else {
            let that = this;

            //存放用户所回答的问卷名称、所回答的答案以及时间
            //必须放在数组内, 便于插入云数据库
            let userAnsCol = [{
                quesName: quesName,
                quesTitle: quesTitle,
                answer: that.data.changed,
                time: util.formatTime(new Date()),
                timeStamp: (new Date()).valueOf()
            }];

            db.collection('userAnswers')
                .where({
                    _openId: userInfoQuestions_2.openId
                }).get().then(res => {
                //res包含查询到的结果
                if (res.data.length === 0) {
                    console.log("temp为空")
                    //未找到此openId, 便写入新的值
                    db.collection('userAnswers').add({
                        data: {
                            userAnsCol: userAnsCol
                        }
                    });
                } else {
                    this.setData({userAnsCol: userAnsCol[0]});
                    db.collection('userAnswers')
                        .where({
                            _openid: userInfoQuestions_2.openId
                        }).update({
                        data: {
                            userAnsCol: dbCmd.push(userAnsCol)
                        }
                    });
                }
            })
            let msg = "感谢填写问卷~";
            pageExit = true;
            this.setData({
                popUpMsg: msg,
                popUpShow: true,
                pageExit: true
            })
        }

    },
    /*
    * 给问卷具体内容按照题号升序排列
    * */
    quesCompare(property) {
        return function (arr_1, arr_2) {
            return arr_1[property] - arr_2[property];
        };
    },
    autoAnswer() {

        /*
        let selectedAsk = event.target.dataset.ask; //被选中的问题
        let answer = event.detail.value; //用户的回答

        this.data.changed[selectedAsk] = answer;
        ansSet.add(selectedAsk);
        this.setData(ansSet);
        * */
        let that = this;
        wx.showLoading({
            title: '加载中',
        })

        setTimeout(function () {
            wx.hideLoading()
            let msg = "您接触到校园贷的概率很低"
            that.setData({
                popUpMsg: msg,
                popUpShow: true,
            })
        }, 2000)


        // console.log("**autoAnswer**")
        // let items = this.data.quesDetail;
        // for (let i = 0; i < this.data.quesDetail.length; i++) {
        //     let ansSum = this.data.quesDetail[i]["ans"].length;
        //     console.log("ansSum: ", ansSum)
        //     console.log("Math.floor(Math.random() * 10) % ansSum:\n\n", Math.floor(Math.random() * 10) % ansSum);
        //     console.log("items[i][\"ans\"][Math.floor(Math.random() * 10) % ansSum]: \n\n", items[i]["ans"][Math.floor(Math.random() * 10) % ansSum]);
        //     items[i]["ans"][Math.floor(Math.random() * 10) % ansSum].checked = true;
        // }
        // console.log(items)
        // this.setData({
        //     quesDetail: items
        // })
    },
    initQuestionPage() {
        for (let i = 0; i < this.data.quesDetail.length; i++) {
            this.data.changed[i] = ''; //把所有问题的回答全部置为空, 以实现初始化回答的目的
        }
        this.setData(this.data.changed);
    },

    /* 收集已被回答的问题
     * @function
     * @param {Object} event 点击事件, 其中携带的有自定义参数: 问题题干ask
    */
    radioChange: function radioChange(event) {
        let selectedAsk = event.target.dataset.ask; //被选中的问题
        let answer = event.detail.value; //用户的回答

        this.data.changed[selectedAsk] = answer;
        ansSet.add(selectedAsk);
        this.setData(ansSet);
    },
    popUpExit() {
        let that = this;
        pageExit = this.data.pageExit;
        if (pageExit) {
            wx.request({
                url: 'https://www.zhanghuajun.top/woodpecker/',
                data: {
                    message: that.data.userAnsCol
                },
                method: 'GET',
                header: {
                    'content-type': 'application/json' // 默认值
                },
                success: function (res) {
                    console.log(res.data);
                    that.setData({
                        returnMsg: res.data
                    })
                },
                fail: function (res) {
                    console.log(".....fail.....");
                }
            });
            // wx.switchTab({
            //     url: "/pages/SupportPage/SupportPage"
            // })
        } else {
            that.setData({
                popUpShow: false
            });
        }
    },
})